<?php

namespace App\Http\Services;

use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Hint;
use App\Http\Model\User;
use App\Http\Model\WishWheel;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FinanceDiamond;
use App\Http\Model\Gift;
use App\Http\Model\LuckDraw;
use App\Http\Model\GiftBag;
use App\Http\Model\Mall;
use App\Http\Model\System;
use App\Http\Services\MsgServices;
use App\Modules\LuckDraw\Models\UserPropModel;
use Carbon\Carbon;
use stdClass;

class WishWheelServices extends CommonServices
{
    protected $userModel;
    protected $userWalletModel;
    protected $financeDiamondModel;
    protected $wishWheelModel;
    protected $giftModel;
    protected $luckDrawModel;
    protected $msgService;
    protected $giftBag_model;
    protected $finance_service;
    protected $systemModel;
    protected $luck_draw_user_prop_model;
    protected $mall_model;
    protected $customService;

    protected $todayPopKey = 'WISHWHEEL:POP';//波波球弹窗协议缓存 set 
    protected $error_log = 'error_wishWheel';

    public function __construct()
    {
        parent::__construct();

        $this->userModel = new User();
        $this->userWalletModel = new FinanceUserWallet();
        $this->financeDiamondModel = new FinanceDiamond();
        $this->wishWheelModel = new WishWheel();
        $this->giftModel = new Gift();
        $this->luckDrawModel = new LuckDraw();
        $this->msgService = new MsgServices();
        $this->giftBag_model = new GiftBag();
        $this->finance_service = new FinanceServices();
        $this->systemModel = new System();
        $this->luck_draw_user_prop_model = new UserPropModel();
        $this->mall_model = new Mall();
        $this->customService = new CustomServices();
    }
    
    /**
     * 新增波波球展示礼物
     */
    public function wishWheelAddGift($giftId, $sort){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($giftId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //新增
            $whiteId = $this->wishWheelModel->wishWheelAddGift($giftId, $sort);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球删除展示礼物
     */
    public function wishWheelDelGift($id){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->wishWheelModel->wishWheelDelGift($id);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 编辑波波球配置
     */
    public function editWishWheelConfig($upData=[]){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($upData)) {
                break;
            }
            $res = $this->wishWheelModel->editWishWheelConfig($upData);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球奖励列表
     */
    public function wishWheelGiftList(){
        $data = [];

        do {
            $list = $this->wishWheelModel->getWishWheelGift();
            $listEx = [];
            if(!empty($list)) {
                foreach($list as $key=>$val) {
                    $item = [];
                    $item['gift_name'] = $val['name'];
                    $item['gift_price'] = $val['price'];
                    $item['gift_image'] = build_image($val['image']);
                    $item['top_right_corner'] = $this->giftGetBanner($val['price']);
                    $item['gift_level'] = $item['gift_level'] = $this->giftGetLevel($val['price']);
                    $listEx[] = $item;
                }
            }

            $data = $listEx;

        } while (false);

        return $data;
    }

    /**
     * 波波球设置奖池开启/关闭
     */
    public function wishWheelSetPoolStatus($poolId, $poolStatus){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolId) || empty($poolStatus)) {
                break;
            }
            //配置
            $config = $this->wishWheelModel->getWishWheelConfig();
            if(empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //奖池
            $pool = $this->wishWheelModel->getWishWheelPool();
            if(empty($pool[$poolId])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $pool[$poolId];
            $poolStatus = ($poolStatus==1) ? 1 : 2;
            //开启
            if($poolStatus == 1) {
                //区间内的奖池必须关闭
                $flag = 0;
                $openPool = [];//已开启的奖池
                foreach($pool as $val) {
                    if($val['status'] != 1) {
                        continue;
                    }
                    $openPool = $val;
                    //个人池不校验次数区间
                    if(in_array($val['pool_type'], [2,3]) || in_array($poolInfo['pool_type'], [2,3])) {
                        continue;
                    }
                    //校验次数区间
                    if($val['pool_type'] == $poolInfo['pool_type']) {
                        if($val['min_num']<=$poolInfo['min_num'] && $poolInfo['min_num']<=$val['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 1:与现有生效奖池'.$val['pool_name'].'（'.$val['id'].'）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                        if($val['min_num']<=$poolInfo['max_num'] && $poolInfo['max_num']<=$val['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 2:与现有生效奖池'.$val['pool_name'].'（'.$val['id'].'）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                        if($poolInfo['min_num']<=$val['min_num'] && $val['min_num']<=$poolInfo['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 3:与现有生效奖池'.$val['pool_name'].'（'.$val['id'].'）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                        if($poolInfo['min_num']<=$val['max_num'] && $val['max_num']<=$poolInfo['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 4:与现有生效奖池'.$val['pool_name'].'（'.$val['id'].'）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                    }
                }
                if($flag == 1) {
                    break;
                }

                //奖池配置数据是否有效
                $poolList = $this->wishWheelModel->getWishWheelPoolConfig($poolId);
                if(empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '获取奖池配置失败';
                    break;
                }
                $flag = 0;
                $giftNumAll = 0;
                $inDiamondNum = 0;//总消耗钻石数
                $outDiamondNum = 0;//总产出钻石数
                foreach($poolList as $val) {
                    if(empty($val['gift_id'])) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '奖池配置 序号'.$val['item_no'].'未配置礼物';
                        $flag = 1;
                        break;
                    }
                    $giftNumAll = $giftNumAll + $val['gift_num'];

                    $giftInfo = $this->giftModel->getGift(['gift_id'=>$val['gift_id']],['gift_id','name','image','price']);
                    $outDiamondNum = $outDiamondNum + ($giftInfo['price']*$val['gift_num']);
                    $inDiamondNum = $inDiamondNum + (200*$config['need_num']*$val['gift_num']);
                }
                if($giftNumAll < 1) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置 礼物数量总和不足1';
                    $flag = 1;
                    break;
                }
                // 奖池的爆出/消耗钻石数小于等于115%才可开启成功
                $rate = round($outDiamondNum/$inDiamondNum, 2);
                if($rate > 1.5) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置 奖池的爆出:'.$outDiamondNum.' /消耗钻石数:'.$inDiamondNum.' 小于等于110%才可开启成功';
                    $flag = 1;
                    break;
                }
                if($flag == 1) {
                    break;
                }

                //和已开启的奖池比较是否礼物一致
                if(!empty($openPool)) {
                    $openPoolList = $this->wishWheelModel->getWishWheelPoolConfig($openPool['id']);
                    if(empty($openPoolList)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '已开启奖池配置异常';
                        break;
                    }
                    $openPoolGift = array_column($openPoolList, 'gift_id', 'item_no');
                    $poolGift = array_column($poolList, 'gift_id', 'item_no');
                    foreach($openPoolGift as $k=>$v) {
                        if($poolGift[$k] != $v) {
                            //$code = Hint::PARAM_ERROR;
                            //$msg = '奖池配置 礼物ID与已开启奖池不一致,奖池序号:'.$k;
                            //$flag = 1;
                            //break;
                        }
                    }
                    if($flag == 1) {
                        break;
                    }
                }
                //重制奖池
                $res = $this->wishWheelPoolReset($poolId);
                if($res['code'] != Hint::SUCCESS) {
                    return $res;
                }
            }

            $res = $this->wishWheelModel->editWishWheelPool($poolId, ['status'=>$poolStatus]);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球保存奖池配置
     */
    public function wishWheelSavePoolConfig($poolId, $poolList){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolId) || empty($poolList)) {
                break;
            }
            $poolInfo = $this->wishWheelModel->getWishWheelPoolById($poolId);
            if(empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if($poolInfo['status'] != 2) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池未关闭';
                break;
            }
            $poolMap = $this->wishWheelModel->getWishWheelPoolConfig($poolId);
            if(empty($poolMap)) {
                $code = Hint::PARAM_ERROR;
                $msg = '获取奖池配置失败';
                break;
            }
            $poolMap = array_column($poolMap, null, 'id');
            //过滤
            $flag = 0;
            foreach($poolList as $val) {
                if(empty($val['gift_id'])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置礼物ID不可为空';
                    $flag = 1;
                    break;
                }
                if(empty($poolMap[$val['id']])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置ID错误';
                    $flag = 1;
                    break;
                }
            }
            if($flag == 1) {
                break;
            }

            //更新
            DB::beginTransaction();
            try {
                foreach($poolList as $val) {
                    $id = $val['id'];
                    $giftId = $val['gift_id'];
                    $giftNum = $val['gift_num'];
                    $res = $this->wishWheelModel->editWishWheelPoolConfig($poolId, $id, $giftId, $giftNum);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $code = Hint::ERROR;
                $msg = '更新系统异常';
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球新增奖池
     */
    public function wishWheelAddPool($poolName, $minNum, $maxNum, $poolType, $ifDefault){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolName)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            if(in_array($poolType, [1]) && (empty($minNum) || empty($maxNum))) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //个人池 默认只能有一个
            if(in_array($poolType, [2,3])){
                if($ifDefault==1){
                    $defaultPool = $this->wishWheelModel->getWishWheelPoolByDefault($poolType);
                    if(!empty($defaultPool)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '个人池 默认只能有一个';
                        break;
                    }
                }
                $minNum = $maxNum = 0;
            }

            //新增
            DB::beginTransaction();
            try {
                $poolId = $this->wishWheelModel->addWishWheelPool($poolName, $minNum, $maxNum, $poolType, $ifDefault);
                if(empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '新增奖池失败';
                    DB::rollBack();
                    break;
                }
                $flag = 0;
                for($i=1;$i<=12;$i++) {
                    $pcId = $this->wishWheelModel->addWishWheelPoolConfig($poolId, $i);
                    if(empty($poolId)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '新增奖池配置失败';
                        $flag = 1;
                        break;
                    }
                }
                if($flag == 1) {
                    DB::rollBack();
                    break;
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $code = Hint::ERROR;
                $msg = '新增系统异常';
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球编辑奖池
     */
    public function wishWheelEditPool($poolId, $poolName, $minNum, $maxNum, $ifDefault){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $this->wishWheelModel->getWishWheelPoolById($poolId);
            if(empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if($poolInfo['status'] != 2) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池未关闭';
                break;
            }
            //个人池 默认只能有一个
            if(in_array($poolInfo['pool_type'], [2,3])){
                if($ifDefault == 1){
                    $defaultPool = $this->wishWheelModel->getWishWheelPoolByDefault($poolInfo['pool_type']);
                    if(!empty($defaultPool) && $defaultPool['id']!=$poolId) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '个人池 默认只能有一个';
                        break;
                    }
                }
                $minNum = $maxNum = 0;
            }

            //更新
            $this->wishWheelModel->editWishWheelPool($poolId, ['pool_name'=>$poolName, 'min_num'=>$minNum, 'max_num'=>$maxNum, 'if_default'=>$ifDefault]);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球奖池更新阀值
     */
    public function wishWheelSetUserPoolConfig($poolId, $upData=[]){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $this->wishWheelModel->getWishWheelPoolById($poolId);
            if(empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if(!in_array($poolInfo['pool_type'], [2,3])){
                $code = Hint::PARAM_ERROR;
                $msg = '奖池不是个人池';
                break;
            }

            //亏损池
            if($poolInfo['pool_type'] == 2) {
                if(!empty($params['in_profit_loss']) && $params['in_profit_loss']<0) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '亏损池进入钻石数必须大于0';
                    break;
                }
                if(!empty($params['in_profit_rate']) && $params['in_profit_loss']<100) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '亏损池进入返奖率必须大于100%';
                    break;
                }
            }

            //盈利池
            if($poolInfo['pool_type'] == 3) {
                if(!empty($params['in_profit_loss']) && $params['in_profit_loss']>0) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '盈利池进入钻石数必须小于0';
                    break;
                }
                if(!empty($params['in_profit_rate']) && $params['in_profit_loss']>100) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '盈利池进入返奖率必须小于100%';
                    break;
                }
            }
            if(!empty($params['out_profit_rate']) && $params['out_profit_rate']<0) {
                $code = Hint::PARAM_ERROR;
                $msg = '个人池移除钻石比例必须大于0';
                break;
            }

            //更新
            $this->wishWheelModel->editWishWheelPool($poolId, $upData);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球更新奖池缓存
     */
    public function wishWheelPoolReset($poolId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if(empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:参数错误';
                    break;
                }
                $poolInfo = $this->wishWheelModel->getWishWheelPoolById($poolId);
                if(empty($poolInfo)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                $poolList = $this->wishWheelModel->getWishWheelPoolConfig($poolId);
                if(empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:数据获取失败';
                    break;
                }
                $poolList = array_column($poolList, 'gift_num', 'id');

                if(in_array($poolInfo['pool_type'], [2,3])) {
                    $this->wishWheelModel->makeWishWheelSelfPoolData($poolId, $poolList);
                }else{
                    $this->wishWheelModel->makeWishWheelPoolData($poolId, $poolList);
                }

            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '更新奖池缓存异常:'.$e->getMessage();
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球奖池配置剩余数量
     */
    public function wishWheelPoolConfigNum($poolId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if(empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                $poolList = $this->wishWheelModel->getWishWheelPoolConfig($poolId);
                if(empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                $hasList = $this->wishWheelModel->getWishWheelPoolData($poolId);
                $hasList = array_column($hasList, 'num', 'id');

                $giftIds = array_column($poolList, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach($poolList as $key=>$val) {
                    $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                    $val['gift_price'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['less_num'] = empty($hasList[$val['id']]) ? 0 : $hasList[$val['id']];
                    $val['draw_num'] = $val['gift_num'] - $val['less_num'];

                    $poolList[$key] = $val;
                }
                $data = $poolList;

            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '异常:'.$e->getMessage();
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球新增白名单
     */
    public function wishWheelAddWhite($userId, $giftId, $adminId=0){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($userId) || empty($giftId) || empty($adminId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //新增
            $whiteId = $this->wishWheelModel->addWishWheelWhite($userId, $giftId, $adminId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球删除白名单
     */
    public function wishWheelDelWhite($whiteId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($whiteId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->wishWheelModel->delWishWheelWhite($whiteId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球删除白名单
     */
    public function wishWheelCancelWhite($whiteId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($whiteId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->wishWheelModel->cancelWishWheelWhite($whiteId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球新增个人池用户
     */
    public function wishWheelAddPoolUser($userId, $poolId, $outDiamondNum, $adminId=0){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($userId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //判断是否存在
            $poolUserInfo = $this->wishWheelModel->getWishWheelPoolUser($userId);
            if(!empty($poolUserInfo)) {
                $code = Hint::PARAM_ERROR;
                $msg = '用户已存在,不可重复添加';
                break;
            }
            //是否在抽取奖池
            $poolUserInfo = $this->wishWheelModel->getWishWheelExtractPoolUser($userId);
            if(!empty($poolUserInfo)) {
                $code = Hint::PARAM_ERROR;
                $msg = '用户已存在,不可重复添加';
                break;
            }

            //获取波波球奖池根据ID
            $poolInfo = $this->wishWheelModel->getWishWheelPoolById($poolId);
            if(empty($poolInfo) || $poolInfo['status']!=1 || !in_array($poolInfo['pool_type'], [2,3])) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池不存在或未开启或不是个人池';
                break;
            }
            if($poolInfo['pool_type']==2 && $outDiamondNum>0) {
                $code = Hint::PARAM_ERROR;
                $msg = '亏损池移除钻石数必须是负数';
                break;
            }
            if($poolInfo['pool_type']==3 && $outDiamondNum<0) {
                $code = Hint::PARAM_ERROR;
                $msg = '盈利池移除钻石数必须是正数';
                break;
            }

            //初始化波波球个人奖池配置数据缓存指定用户
            $poolConfigMap = $this->wishWheelModel->getWishWheelPoolConfig($poolId);
            if(empty($poolConfigMap)) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池配置获取失败';
                break;
            }
            $poolConfigMap = array_column($poolConfigMap, 'gift_num', 'id');
            $this->wishWheelModel->makeWishWheelSelfPoolDataByPoolIdUserId($poolId, $userId, $poolConfigMap);

            //新增
            $whiteId = $this->wishWheelModel->addWishWheelPoolUser($userId, $adminId, $poolId, $outDiamondNum);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球删除个人池用户
     */
    public function wishWheelDelPoolUser($id, $adminId=0){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //判断是否存在
            $poolUserInfo = $this->wishWheelModel->getWishWheelPoolUserById($id);
            if(empty($poolUserInfo) || $poolUserInfo['is_delete']==1) {
                break;
            }

            $res = $this->wishWheelModel->wishWheelDelPoolUser($id, $poolUserInfo['user_id'], $adminId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //查看个人奖池配置剩余数量
    public function wishWheelPoolSelfConfigNum($poolId, $userId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if(empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                $poolInfo = $this->wishWheelModel->getWishWheelPoolById($poolId);
                if(empty($poolInfo)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                if(!in_array($poolInfo['pool_type'], [2,3])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '不是个人奖池';
                    break;
                }

                //用户是否在
                $poolUserInfo = $this->wishWheelModel->getWishWheelPoolUser($userId);
                if(empty($poolUserInfo) || $poolUserInfo['pool_id']!=$poolId) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '用户不在此个人池中';
                    break;
                }

                $poolList = $this->wishWheelModel->getWishWheelPoolConfig($poolId);
                if(empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:数据获取失败';
                    break;
                }

                $hasList = $this->wishWheelModel->getWishWheelSelfPoolData($poolId, $userId);
                $hasList = array_column($hasList, 'num', 'id');

                $giftIds = array_column($poolList, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach($poolList as $key=>$val) {
                    $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                    $val['gift_price'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['less_num'] = empty($hasList[$val['id']]) ? 0 : $hasList[$val['id']];
                    $val['draw_num'] = $val['gift_num'] - $val['less_num'];

                    $poolList[$key] = $val;
                }
                $data = $poolList;

            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '异常:'.$e->getMessage();
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球新增奖池白名单
     */
    public function wishWheelAddPoolWhite($userId, $giftId, $adminId=0){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($userId) || empty($giftId) || empty($adminId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //个人池用户
            $poolUser = $this->wishWheelModel->getWishWheelPoolUserId($userId);
            if(!empty($poolUser)) {
                $code = Hint::PARAM_ERROR;
                $msg = '用户在个人池 不可添加奖池白名单';
                break;
            }

            //获取用户当前抽奖的奖池
            //奖池
            $pool = $this->wishWheelModel->getWishWheelPool();
            $basePoolList = [];//普通池的
            $userPoolList = [];//用户个人池的
            foreach($pool as $val) {
                if($val['status'] != 1){
                    continue;
                }
                //奖池配置数据
                $poolConfig = $this->wishWheelModel->getWishWheelPoolConfig($val['id']);
                if(empty($poolConfig)) {
                    continue;
                }
                $val['poolConfig'] = $poolConfig;
                //普通池
                if($val['pool_type'] == 1) {
                    $basePoolList[] = $val;
                }
            }
            $poolList = [];//已开启的奖池
            if(empty($poolUser)) {
                $poolList = $basePoolList;
            }
            if(empty($poolList)) {
                $code = Hint::WAIT_OPEN;
                $msg = '创建失败，当前没有已开启的奖池';
                break;
            }

            //用户总抽奖记录数
            $drawNumNow = $drawNum = $this->wishWheelModel->getUserWishWheelDrawNumByWeek($userId);
            $drawNumNow = $drawNumNow + 1;

            $usePool = [];//使用的奖池
            //在范围的
            foreach($poolList as $val) {
                if($val['min_num']<=$drawNumNow && $drawNumNow<=$val['max_num']) {
                    $usePool = $val;
                }
            }
            //上一个
            $prevNum = 0;
            if(empty($usePool)) {
                foreach($poolList as $val) {
                    if($val['max_num']<=$drawNumNow && $prevNum<=$val['max_num']) {
                        $usePool = $val;
                        $prevNum = $val['max_num'];
                    }
                }
            }
            //下一个
            $nextNum = 0;
            if(empty($usePool)) {
                foreach($poolList as $val) {
                    if($val['min_num']>=$drawNumNow && ($nextNum==0 || $nextNum>=$val['min_num'])) {
                        $usePool = $val;
                        $nextNum = $val['min_num'];
                    }
                }
            }
            //还是没有取第一个
            if(empty($usePool)) {
                $usePool = $poolList[0];
            }
            $poolId = $usePool['id'];

            $poolConfigId = 0;
            foreach($usePool['poolConfig'] as $val) {
                if($val['gift_id'] == $giftId) {
                    $poolConfigId = $val['id'];

                }
            }
            if(empty($poolConfigId)) {
                $code = Hint::WAIT_OPEN;
                $msg = '创建失败，用户将抽取奖池配置中无此礼物';
                break;
            }

            //自指定奖池中抽取指定的余量
            if(in_array($usePool['pool_type'], [2,3])) {
                //个人池
                $res = $this->wishWheelModel->drawWishWheelAppoint($usePool['id'], $poolConfigId, $userId);
            }else{
                //普通
                $res = $this->wishWheelModel->drawWishWheelAppoint($usePool['id'], $poolConfigId, 0);
            }
            if($res) {
                //新增
                $whiteId = $this->wishWheelModel->addWishWheelWhite($userId, $giftId, $adminId, $poolId);
                if(!$whiteId) {
                    $code = Hint::WAIT_OPEN;
                    $msg = '创建失败，奖池余量扣除成功,数据写入失败';
                    break;
                }
            }else{
                $code = Hint::WAIT_OPEN;
                $msg = '创建失败，奖池无余量';
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球奖池配置获取
     */
    public function wishWheelConfig($userId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        write_log('zzq', "1", []);
        do {
            write_log('zzq', "2", []);

            //配置
            $config = $this->wishWheelModel->getWishWheelConfig();
            if(empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //货币价格
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo(1000);
            $luckDrawPrice = 200;
            //获取用户钱包信息
            $userWaltInfo = $this->userWalletModel->get_wallet($userId);

            $data['need_num'] = $config['need_num'];
            // if ($config['draw_num_1'] > 0) {
                $data['draw_num_1'] = $config['draw_num_1'];
                $data['draw_img_1a'] = build_image($config['draw_img_1a']);
                $data['draw_img_1b'] = build_image($config['draw_img_1b']);
            // }
            // if ($config['draw_num_2'] > 0) {
                $data['draw_num_2'] = $config['draw_num_2'];
                $data['draw_img_2a'] = build_image($config['draw_img_2a']);
                $data['draw_img_2b'] = build_image($config['draw_img_2b']);    
            // }
            // if ($config['draw_num_3'] > 0) {
                $data['draw_num_3'] = $config['draw_num_3'];
                $data['draw_img_3a'] = build_image($config['draw_img_3a']);
                $data['draw_img_3b'] = build_image($config['draw_img_3b']);    
            // }
            $data['rule'] = $config['rule'];
            $data['today_pop'] = 0;//当时是否弹出
	    $data['pop_msg'] = '参与甜蜜告白需消耗告白币，开启钻石自动购买幻境头像框可默认消耗附赠告白币参与游戏'.PHP_EOL.'1张告白币='.$luckDrawPrice.'钻石/每次探索消耗17张告白币'.PHP_EOL.'您的钻石余额：'.$userWaltInfo['diamond_balance'];
	    if(Redis::SISMEMBER($this->todayPopKey,$userId)){
                $data['today_pop'] = 1;
            }

            //奖池
            $poolId = 0;
            $pool = $this->wishWheelModel->getWishWheelPool();
            foreach($pool as $val) {
                if($val['status'] == 1){
                    $poolId = $val['id'];
                }
            }
            if(empty($poolId)) {
                $code = Hint::WAIT_OPEN;
                break;
            }
            //奖池配置数据
            $poolList = $this->wishWheelModel->getWishWheelPoolConfig($poolId);
            if(empty($poolList)) {
                $code = Hint::WAIT_OPEN;
                break;
            }
            $giftIds = array_column($poolList, 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
            $giftList = array_column($giftList, null, 'gift_id');

            $data['pool_list'] = [];
            foreach($poolList as $key=>$val) {
                $item = [];
                $item['id'] = $val['id'];
                $item['pool_id'] = $val['pool_id'];
                $item['item_no'] = $val['item_no'];
                $item['gift_id'] = $val['gift_id'];
                $item['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                $item['gift_price'] = (int) (empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price']);
                $item['gift_image'] = empty($giftList[$val['gift_id']]['image']) ? '' : build_image($giftList[$val['gift_id']]['image']);
                $item['top_right_corner'] = $this->giftGetBanner($val['gift_id']);
                $data['pool_list'][$key] = $item;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球自动兑换货币弹窗
     */
    public function wishWheelPop($userId, $num, $roomId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = new stdClass;
        $luckId = 1000;
        $todayPop = 0;
        $now = time();
        do {
            $num = abs($num);
            //配置
            $config = $this->wishWheelModel->getWishWheelConfig();
            if(empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $needNum = $config['need_num'] * $num;
            //用户货币数量
            $userLuckDrawProp = $this->luckDrawModel->getLuckDrawUserProp($userId, $luckId);

            //货币价格
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo($luckId);
            $luckDrawPrice = 200;

            //获取用户钱包信息
            $userWaltInfo = $this->userWalletModel->get_wallet($userId);

            //查看今日是否弹窗
            if(Redis::SISMEMBER($this->todayPopKey,$userId)){
                $todayPop = 1;
            }
            if($userLuckDrawProp['avail'] < $needNum) {
                $code = Hint::SUCCESS;
		$msg = '参与甜蜜告白需消耗告白币，开启钻石自动购买幻境头像框可默认消耗附赠告白币参与游戏'.PHP_EOL.'一张告白币='.$luckDrawPrice.'钻石/每次探索消耗17张告白币'.PHP_EOL.'您的钻石余额：'.$userWaltInfo['diamond_balance'];
                $data = [
                    'pop_msg' => $msg,
                    'is_open' => $todayPop,
                ];
            }else{
                $data = [
                    'pop_msg' => $msg,
                    'is_open' => 1,
                ]; 
            }
        }while(false);
        return compact('code','data','msg');
    }

    /**
     * 确认弹窗协议
     */
    public function wishWheelConfirm($userId){
        do{
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            if(Redis::SISMEMBER($this->todayPopKey,$userId)){
                $code = Hint::ERR_NORMAL;
                $msg = '已确认';
                break;
            }
            Redis::SADD($this->todayPopKey,$userId);
            $endDay = Carbon::today()->endOfDay()->toDateTimeString();
            $diffTime = (new Carbon)->diffInSeconds($endDay);
            Redis::EXPIRE($this->todayPopKey,$diffTime);
        }while(false);
        
        return compact('code','data','msg');
    }

    /**
     * 波波球抽奖
     */
    public function wishWheelDraw($userId, $num, $roomId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $luckId = 1000;
        $now = time();
        do {
            $num = abs($num);
            //配置
            $config = $this->wishWheelModel->getWishWheelConfig();
            if(empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $needNum = $config['need_num'] * $num;

            //个人池用户
            $poolUser = $this->wishWheelModel->getWishWheelPoolUserId($userId);

            //抽取奖池
            $extractPoolUserInfo = $this->wishWheelModel->getWishWheelExtractPoolUserOpen($userId);

            //获取用户当前抽奖的奖池
            //奖池
            $pool = $this->wishWheelModel->getWishWheelPool();
            $basePoolList = [];//普通池的
            $userPoolList = [];//用户个人池的
            foreach($pool as $val) {
                if($val['status'] != 1){
                    continue;
                }
                //奖池配置数据
                $poolConfig = $this->wishWheelModel->getWishWheelPoolConfig($val['id']);
                if(empty($poolConfig)) {
                    continue;
                }
                $val['poolConfig'] = $poolConfig;
                //普通池
                if($val['pool_type'] == 1) {
                    $basePoolList[] = $val;
                }
                //用户个人池
                if(in_array($val['pool_type'], [2,3])) {
                    if(!empty($poolUser) && !empty($poolUser['pool_id']) && $val['id']==$poolUser['pool_id']){
                        $userPoolList[] = $val;
                    }
                }
            }
            $poolList = [];//已开启的奖池
            $giftToItemNo = [];//奖池礼物对应的奖池序号
            $ifdrawInUserPool = 0;//是否在个人池抽奖 0=否 1=是
            if(!empty($poolUser) && !empty($userPoolList)) {
                $poolList = $userPoolList;
                $ifdrawInUserPool = 1;
                $extractPoolUserInfo = [];//个人池抽奖的话抽取奖池设为空
            }else{
                $poolList = $basePoolList;
            }
            if(empty($poolList)) {
                $code = Hint::WAIT_OPEN;
                break;
            }
            $giftToItemNo = array_column($poolList[0]['poolConfig'], 'item_no', 'gift_id');

            //货币价格
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo($luckId);
            $luckDrawPrice = 200;

            //用户货币数量
            $userLuckDrawProp = $this->luckDrawModel->getLuckDrawUserProp($userId, $luckId);
            if($userLuckDrawProp['avail'] < $needNum) {
                //新逻辑自动转换兑换货币,在redis名单中的代表新版本用户抽奖
                if(Redis::SISMEMBER($this->todayPopKey,$userId)){
                    $changeStatus = $this->autoExchangeCard($userLuckDrawProp, $needNum, $luckDrawPrice, $userId);
                    if($changeStatus['code'] != Hint::SUCCESS){
                        $code = $changeStatus['code'];
                        $msg = $changeStatus['msg'];
                        break;
                    }
                }else{
                    $code = Hint::LUCK_DRAW_PROP_NOT_ENOUGH;
                    $msg = '货币数量不足';
                    break;
                } 
            }

            //扣告白币
            $decrRes = $this->luckDrawModel->decrLuckDrawUserProp($userId, $luckId, $needNum);
            if(!$decrRes) {
                $code = Hint::LUCK_DRAW_PROP_NOT_ENOUGH;
                $msg = '货币数量不足';
                break;
            }

            //人气票发放
            $this->customService->SendTicket($userId, $needNum, $luckDrawPrice);

            //用户信息
            $userInfo = $this->userModel->get_users_by_ids([$userId]);
            $userInfo = array_column($userInfo, null, 'user_id');
            $userInfo = $userInfo[$userId];

            //用户总抽奖记录数
            if($ifdrawInUserPool) {
                //个人池用户
                $drawNumNow = $drawNum = $poolUser['draw_num'];
            }else{
                //普通
                $drawNumNow = $drawNum = $this->wishWheelModel->getUserWishWheelDrawNumByWeek($userId);
            }

            //白名单
            $whiteListNow = $whiteList = $this->wishWheelModel->getWishWheelWhite($userId);

            //订单记录
            $orderInfo = [
                'user_id' => $userId,
                'num' => $num,
                'prop_num' => $needNum,
                'prop_diamond_num' => $needNum*$luckDrawPrice,
                'reward_diamond_num' => 0,
                'created_at' => date('Y-m-d H:i:s', $now),
            ];
            $orderId = $this->wishWheelModel->addWishWheelOrder($orderInfo);
            if(empty($orderId)) {
                $code = Hint::ERR_SYS_FAIL;
                break;
            }

            //抽奖
            $drawLogList = [];
            try {
                for($i=1;$i<=$num;$i++) {
                    $drawNumNow = $drawNumNow + 1;
                    $drawLog = [];
                    $drawLog['draw_no'] = $i;
                    $drawLog['gift_id'] = 0;
                    $drawLog['white_id'] = 0;
                    $drawLog['pool_id'] = 0;
                    $drawLog['item_no'] = 0;
                    //白名单
                    if(!empty($whiteListNow)) {
                        $whiteInfo = array_shift($whiteListNow);
                        $drawLog['gift_id'] = $whiteInfo['gift_id'];
                        $drawLog['white_id'] = $whiteInfo['id'];
                        $drawLog['item_no'] = empty($giftToItemNo[$whiteInfo['gift_id']]) ? 11 : $giftToItemNo[$whiteInfo['gift_id']];
                    }else{
                        do {
                            //抽取奖池判断
                            if(!empty($extractPoolUserInfo)) {
                                $rewardGiftId = $this->wishWheelModel->getWishWheelExtractPoolDataOne($extractPoolUserInfo['extract_pool_id']);
                                if(!empty($rewardGiftId)) {
                                    $drawLog['gift_id'] = $rewardGiftId;
                                    $drawLog['white_id'] = 0;
                                    $drawLog['item_no'] = empty($giftToItemNo[$rewardGiftId]) ? 11 : $giftToItemNo[$rewardGiftId];
                                    $drawLog['pool_id'] = $extractPoolUserInfo['pool_id'];
                                    $drawLog['extract_pool_id'] = $extractPoolUserInfo['extract_pool_id'];
                                    break;
                                }
                            }

                            $usePool = [];//使用的奖池
                            //在范围的
                            foreach($poolList as $val) {
                                if($val['min_num']<=$drawNumNow && $drawNumNow<=$val['max_num']) {
                                    $usePool = $val;
                                }
                            }
                            //上一个
                            $prevNum = 0;
                            if(empty($usePool)) {
                                foreach($poolList as $val) {
                                    if($val['max_num']<=$drawNumNow && $prevNum<=$val['max_num']) {
                                        $usePool = $val;
                                        $prevNum = $val['max_num'];
                                    }
                                }
                            }
                            //下一个
                            $nextNum = 0;
                            if(empty($usePool)) {
                                foreach($poolList as $val) {
                                    if($val['min_num']>=$drawNumNow && ($nextNum==0 || $nextNum>=$val['min_num'])) {
                                        $usePool = $val;
                                        $nextNum = $val['min_num'];
                                    }
                                }
                            }
                            //还是没有取第一个
                            if(empty($usePool)) {
                                $usePool = $poolList[0];
                            }

                            //抽取 
                            if(in_array($usePool['pool_type'], [2,3])) {
                                //个人池
                                $poolConfigId = $this->wishWheelModel->drawWishWheelUser($usePool['id'], $userId);
                            }else{
                                //普通
                                $poolConfigId = $this->wishWheelModel->drawWishWheel($usePool['id']);
                            }
                            $poolConfigMap = array_column($usePool['poolConfig'], null, 'id');

                            $drawLog['gift_id'] = $poolConfigMap[$poolConfigId]['gift_id'];
                            $drawLog['white_id'] = 0;
                            $drawLog['pool_id'] = $poolConfigMap[$poolConfigId]['pool_id'];
                            $drawLog['item_no'] = $poolConfigMap[$poolConfigId]['item_no'];

                        } while (false);
                    }

                    $drawLogList[] = $drawLog;
                }
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                write_log('error_wishwheel', 'wishWheelDraw 抽奖失败', ['orderId'=>$orderId, 'message'=>$e->getMessage(), 'line'=>$e->getLine()]);
                break;
            }

            //累加用户总抽奖记录数
            $this->wishWheelModel->incrUserDrawWeekNum($userId, $num);

            $giftIds = array_column($drawLogList, 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
            $giftList = array_column($giftList, null, 'gift_id');

            //抽奖保存
            DB::beginTransaction();
            try {
                $rewardDiamondNumAll = 0;
                //新增波波球抽奖记录
                foreach($drawLogList as $key=>$val) {
                    $val['order_id'] = $orderId;
                    $val['user_id'] = $userId;
                    $val['prop_num'] = $config['need_num'];
                    $val['gift_num'] = 1;
                    $val['prop_diamond_num'] = $val['prop_num'] * $luckDrawPrice;
                    $val['reward_diamond_num'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['created_at'] = date('Y-m-d H:i:s', $now);
                    $this->wishWheelModel->addWishWheelDraw($val);

                    //奖励价值钻石数
                    $rewardDiamondNumAll = $rewardDiamondNumAll + $val['reward_diamond_num'];

                    //白名单
                    if(!empty($val['white_id'])) {
                        $this->wishWheelModel->updateWishWheelWhite($val['white_id'], $orderId);
                    }

                    //送礼物
                    $this->giftBag_model->inc((int)$userId, 0, (int)$val['gift_id'], 1, 1011);

                    $drawLogList[$key] = $val;
                }
                //更新订单
                $this->wishWheelModel->updateWishWheelDraw($orderId, $rewardDiamondNumAll);
                //更新个人池用户记录
                if($ifdrawInUserPool && $val['white_id']==0) {
                    $this->wishWheelModel->updateWishWheelUserPoolLog($poolUser['id'], $orderInfo['prop_diamond_num'], $rewardDiamondNumAll, $orderInfo['num']);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_wishwheel', 'wishWheelDraw 抽奖保存', ['orderId'=>$orderId, 'drawLogList'=>$drawLogList, 'message'=>$e->getMessage(), 'line'=>$e->getLine()]);
                break;
            }
            //更新波波球用户每日抽奖数据统计缓存
            $this->wishWheelModel->updateWishWheelUserDay($userId, $orderInfo['prop_diamond_num'], $rewardDiamondNumAll, $orderInfo['num']);

            //个人池用户自动处理移入移出
            $this->wishWheelModel->handleWishWheelUserPool($userId, $poolUser);

            //汇总返回值
            $resList = [];
            foreach($drawLogList as $val) {
                $k = $val['item_no'].'|'.$val['gift_id'];
                if(isset($resList[$k])) {
                    $item = $resList[$k];
                    $item['gift_num'] = $item['gift_num'] + 1;
                }else{
                    $item = [];
                    $item['item_no'] = $val['item_no'];
                    $item['gift_id'] = $val['gift_id'];
                    $item['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                    $item['gift_price'] = (int) (empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price']);
                    $item['gift_image'] = empty($giftList[$val['gift_id']]['image']) ? '' : build_image($giftList[$val['gift_id']]['image']);
                    $item['top_right_corner'] = $this->giftGetBanner($item['gift_price']);
                    $item['gift_level'] = $this->giftGetLevel($item['gift_price']);
                    $item['gift_num'] = $item['gift_num'] + 1;
                }

                $resList[$k] = $item;
            }
            $resList = array_values($resList);
            array_multisort(array_column($resList, 'gift_price'), SORT_DESC, $resList);

            //房间内游戏公屏游戏消息
            if($roomId > 10) {
                //查询飘屏中设置的飘屏限制钻石数,因为公屏限制和飘屏限制一致
                $fullScreen = $this->systemModel->getFullScreen(63);
                if (empty($fullScreen)) {
                    return false;
                }
                foreach($resList as $val) {
                    if($val['gift_price']>=$fullScreen['special_full_screen_diamond']){
                        //$this->msgService->roomGameMsg($roomId, ['nickname'=>$userInfo['nickname'], 'user_id'=>$userInfo['user_id'], 'placeName'=>'在甜蜜告白中', 'giftName'=>$val['gift_name'], 'giftPrice'=>$val['gift_price'], 'giftNum'=>$val['gift_num'], 'giftImg' => $val['gift_image']]);
                    }
                    if($val['gift_price']>=$fullScreen['special_full_screen_diamond']){
                        $msg= $this->msgService->roomGameMsg2($roomId,['nickname'=>$userInfo['nickname'], 'user_id'=>$userInfo['user_id'], 'placeName'=>'在甜蜜告白中', 'giftName'=>$val['gift_name'], 'giftPrice'=>$val['gift_price'], 'giftNum'=>$val['gift_num'], 'giftImg' => $val['gift_image']]);
//                        write_log('sendFullScreen', '发送世界消息:liya', $msg);
                    }
                }
            }

            $data['list'] = $resList;
            $data['order_id'] = $orderId;
            $data['reward_diamond_num'] = $rewardDiamondNumAll;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球发飘屏
     */
    public function wishWheelDrawFull($orderId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $luckId = 1000;
        $now = time();
        do {
            if(empty($orderId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $orderInfo = $this->wishWheelModel->orderAwardList($orderId);
            if(empty($orderInfo)) {
                break;
            }
            //配置
            $config = $this->wishWheelModel->getWishWheelConfig();
            if(empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //告白币价格
            $luckDrawInfo = $this->luckDrawModel->luckDrawInfo($luckId);
            $luckDrawPrice = 200;

            //用户信息
            $userInfo = $this->userModel->get_users_by_ids([$orderInfo['user_id']]);
            $userInfo = array_column($userInfo, null, 'user_id');
            $userInfo = $userInfo[$orderInfo['user_id']];

            $giftIds = array_column($orderInfo['drawList'], 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
            $giftList = array_column($giftList, null, 'gift_id');

            //飘屏
            foreach($orderInfo['drawList'] as $val) {
                $giftPrice = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                $giftName = empty($giftList[$val['gift_id']]['name']) ? 0 : $giftList[$val['gift_id']]['name'];
                $rate = ($val['reward_diamond_num']/$val['prop_diamond_num'])*100;
                if($rate >= $config['full_rate']) {
                    $this->msgService->sendFullScreen(63,null,['userName'=>$userInfo['nickname'], 'diamondNum'=>$giftPrice, 'giftName'=>$giftName, 'giftNum'=>$val['gift_num']],[],['giftPrice'=>$giftPrice]);
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //礼物获取角标
    public function giftGetBanner($price=0){
        $icon = '';
        if($price >= 520 && $price <= 1999){
            //高级icon
            $icon = build_image('/icon/-Km.webp');
        }
        if($price >= 2000 && $price <= 9999){
            //稀有icon
            $icon = build_image('/icon/MiU.webp');
        }
        if($price >= 10000 && $price <= 66666){
            //传说icon
            $icon = build_image('/icon/tj8.webp');
        }
        if($price >= 99999){
            //至尊icon
            $icon = build_image('/icon/JIg.webp');
        }
        return $icon;
    }

    //礼物获取等级
    public function giftGetLevel($price = 0){
        $level = 0;
        if($price >= 520 && $price <= 1999){
            //高级
            $level = 1;
        }
        if($price >= 2000 && $price <= 9999){
            //稀有
            $level = 2;
        }
        if($price >= 10000){
            //传说
            $level = 3;
        }
        return $level;
    }

    /**
     * 波波球用户中奖记录列表
     */
    public function wishWheelAwardListByUserId($orderId, $limit, $userId=''){
        $data = [];
        do {
            $where['user_id'] = $userId;
            $list = $this->wishWheelModel->awardList($orderId, $limit, $where);
            $listEx = [];
            if(!empty($list)) {
                $userIds = array_column($list, 'user_id');
                $userList = $this->userModel->get_users_by_ids($userIds);
                $userList = array_column($userList, null, 'user_id');

                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds,['gift_id','name','image','price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach($list as $key=>$val) {
                    if(empty($userList[$val['user_id']])) {
                        continue;
                    }
                    if(empty($giftList[$val['gift_id']])) {
                        continue;
                    }

                    $val['nickname'] = $userList[$val['user_id']]['nickname'];
                    $val['uuid'] = $userList[$val['user_id']]['user_uid'];
                    $val['avatar'] = build_image($userList[$val['user_id']]['images'][0]);
                    $val['gift_name'] = $giftList[$val['gift_id']]['name'];
                    $val['gift_image'] = build_image($giftList[$val['gift_id']]['image']);
                    $val['gift_price'] = $giftList[$val['gift_id']]['price'];

                    $listEx[] = $val;
                }
            }

            $data['list'] = $listEx;

        } while (false);

        return $data;
    }

    /**
     * 波波球今日中奖记录列表V2
     */
    public function wishWheelDrawAwardListV2($page, $limit, $userId=''){
        $data = [];
        do {
            $where = [];
            //今天
            $where['created_at_st'] = date('Y-m-d 00:00:00', time());
            $list = $this->wishWheelModel->awardListV2($page, $limit, $where);
            $listEx = [];
            if(!empty($list)) {
                $userIds = array_column($list, 'user_id');
                $userList = $this->userModel->get_users_by_ids($userIds);
                $userList = array_column($userList, null, 'user_id');

                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds,['gift_id','name','image','price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach($list as $key=>$val) {
                    if(empty($userList[$val['user_id']])) {
                        continue;
                    }
                    if(empty($giftList[$val['gift_id']])) {
                        continue;
                    }

                    $val['nickname'] = $userList[$val['user_id']]['nickname'];
                    $val['uuid'] = $userList[$val['user_id']]['user_uid'];
                    $val['avatar'] = build_image($userList[$val['user_id']]['images'][0]);
                    $val['gift_name'] = $giftList[$val['gift_id']]['name'];
                    $val['gift_image'] = build_image($giftList[$val['gift_id']]['image']);
                    $val['gift_price'] = $giftList[$val['gift_id']]['price'];

                    $listEx[] = $val;
                }
            }

            $data['list'] = $listEx;

        } while (false);

        return $data;
    }

    /**
     * 波波球今日中奖记录列表
     */
    public function wishWheelDrawAwardList($orderId, $limit, $userId=''){
        $data = [];
        do {
            $where = [];
            //今天
            $where['created_at_st'] = date('Y-m-d 00:00:00', time());
            $list = $this->wishWheelModel->awardList($orderId, $limit, $where);
            $listEx = [];
            if(!empty($list)) {
                $userIds = array_column($list, 'user_id');
                $userList = $this->userModel->get_users_by_ids($userIds);
                $userList = array_column($userList, null, 'user_id');

                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds,['gift_id','name','image','price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach($list as $key=>$val) {
                    if(empty($userList[$val['user_id']])) {
                        continue;
                    }
                    if(empty($giftList[$val['gift_id']])) {
                        continue;
                    }
                    
                    $val['nickname'] = $userList[$val['user_id']]['nickname'];
                    $val['uuid'] = $userList[$val['user_id']]['user_uid'];
                    $val['avatar'] = build_image($userList[$val['user_id']]['images'][0]);
                    $val['gift_name'] = $giftList[$val['gift_id']]['name'];
                    $val['gift_image'] = build_image($giftList[$val['gift_id']]['image']);
                    $val['gift_price'] = $giftList[$val['gift_id']]['price'];

                    $listEx[] = $val;
                }
            }

            $data['list'] = $listEx;

        } while (false);

        return $data;
    }

    /**
     * 自动兑换货币
     */
    public function autoExchangeCard($userLuckDrawProp, $needNum, $luckDrawPrice, $userId){
        do{
            $code = Hint::SUCCESS;
            $msg = '';
            $data = [];
            $key = 'WISHWHEEL:EXCHANGE
            :'.$userId;
            $ifLock = redis_lock($key, 1);
            if (!$ifLock){
                $code = Hint::ERR_NORMAL;
                $msg = '同一时间请勿重复请求';
                break;
            }
            $buyNum = $needNum - $userLuckDrawProp['avail'];
            $costDiamond = $buyNum * $luckDrawPrice;
            //查看用户钱包
            $userWaltInfo = $this->userWalletModel->get_wallet($userId);
            if($userWaltInfo['diamond_balance'] < $costDiamond){
                $code = Hint::ERR_NORMAL;
                $msg = '钻石不足';
                break;
            }
            try{
                DB::beginTransaction();
                //扣钻石
                $this->financeDiamondModel->inc($userId, 0, 0, 6, -$costDiamond , '自动兑换告白币*'.$buyNum);
                //发放告白币
                $this->luck_draw_user_prop_model->add(1000,$userId,$buyNum);
                //赠送头像框
                $goodId = 13;
                $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
                if(empty($goodInfo)) {
                    return [Hint::ERR_NORMAL, null];
                }
                $skuList = $this->mall_model->getSkuDataByGoods($goodId);
                if(empty($skuList[0])) {
                    return [Hint::ERR_NORMAL, null];
                }
                $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
                $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
                $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
                //有效期
                $timeLimit = $buyNum*3600;
                //商品增加
                $this->mall_model->shoppingAct(
                    11,
                    $userId,
                    $goodId,
                    $goodMap[$goodId]['goods_name'],
                    $goodMap[$goodId]['goods_type'],
                    $goodMap[$goodId]['sku_id'],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2
                );
		DB::commit();
		redis_unlock($key);
            }catch(\Exception $e){
                DB::rollBack();
                write_log($this->error_log,'ERROR 扣除钻石失败',['msg'=>$e->getMessage(),'line'=>$e->getLine(),'costDiamond'=>$costDiamond]);
                $code = Hint::ERR_NORMAL;
                $msg = '钻石不足';
                break;
            }
            
        }while(false);
        return compact('code','data','msg');
        
    }
    /**
     * 波波球每日统计
     */
    public function statisticalData($ymd){
        do {
            $dateSt = date('Y-m-d 00:00:00', strtotime($ymd));
            $dateEt = date('Y-m-d 23:59:59', strtotime($ymd));
            $info = $this->wishWheelModel->wishWheelStatistics($dateSt, $dateEt);

            $data = [];
            $data['ymd'] = date('Ymd', strtotime($ymd));
            $data['user_num'] = empty($info['user_num']) ? 0 : $info['user_num'];
            $data['draw_num'] = empty($info['draw_num']) ? 0 : $info['draw_num'];
            $data['prop_num'] = empty($info['prop_num']) ? 0 : $info['prop_num'];
            $data['prop_diamond_num'] = empty($info['prop_diamond_num']) ? 0 : $info['prop_diamond_num'];
            $data['reward_diamond_num'] = empty($info['reward_diamond_num']) ? 0 : $info['reward_diamond_num'];
            $data['profit_loss'] = $data['prop_diamond_num'] - $data['reward_diamond_num'];

            $this->wishWheelModel->addWishWheelStatistics($data);

        } while (false);

        return $data;
    }

    /**
     * 波波球新增抽取奖池
     */
    public function wishWheelAddExtractPool($poolName, $poolId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($poolName) || empty($poolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //新增
            $poolId = $this->wishWheelModel->addWishWheelExtractPool($poolName, $poolId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球编辑抽取奖池
     */
    public function wishWheelEditExtractPool($extractPoolId, $poolName){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($extractPoolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $this->wishWheelModel->getWishWheelExtractPoolById($extractPoolId);
            if(empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //更新
            $this->wishWheelModel->editWishWheelExtractPool($extractPoolId, ['pool_name'=>$poolName]);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球设置抽取奖池开启/关闭
     */
    public function wishWheelSetExtractPoolStatus($extractPoolId, $poolStatus){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($extractPoolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $this->wishWheelModel->getWishWheelExtractPoolById($extractPoolId);
            if(empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //更新
            $this->wishWheelModel->editWishWheelExtractPool($extractPoolId, ['status'=>$poolStatus]);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球新增抽取奖池用户
     */
    public function wishWheelAddExtractPoolUser($userId, $extractPoolId, $adminId=0, $ifConfirm=0){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($userId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //抽取奖池信息
            $poolInfo = $this->wishWheelModel->getWishWheelExtractPoolById($extractPoolId);
            if(empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //是否在抽取奖池
            $poolUserInfo = $this->wishWheelModel->getWishWheelExtractPoolUser($userId);
            if(!empty($poolUserInfo)) {
                $code = Hint::PARAM_ERROR;
                $msg = '用户已存在,不可重复添加';
                break;
            }
            //是否在个人池
            $poolUserInfo = $this->wishWheelModel->getWishWheelPoolUser($userId);
            if(!empty($poolUserInfo)) {
                if(empty($ifConfirm)) {
                    $code = Hint::USER_IS_EXIST;
                    $msg = '用户已存在个人池 不可添加';
                    break;
                }else{
                    //移除个人池
                    $this->wishWheelDelPoolUser($poolUserInfo['id'], $adminId);
                }
            }

            //新增
            $whiteId = $this->wishWheelModel->addWishWheelExtractPoolUser($userId, $extractPoolId, $adminId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球删除抽取奖池用户
     */
    public function wishWheelDelExtractPoolUser($id, $adminId=0){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //判断是否存在
            $poolUserInfo = $this->wishWheelModel->getWishWheelExtractPoolUserById($id);
            if(empty($poolUserInfo) || $poolUserInfo['is_delete']==1) {
                break;
            }

            $res = $this->wishWheelModel->wishWheelDelExtractPoolUser($id, $adminId);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球新增抽取奖池礼物
     */
    public function wishWheelAddExtractPoolGift($extractPoolId, $extractInfo, $adminId=0){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($extractPoolId) || empty($extractInfo) || empty($adminId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //查询
            $poolInfo = $this->wishWheelModel->getWishWheelExtractPoolById($extractPoolId);
            if(empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //获取剩余数量
            $lessList = $this->wishWheelPoolConfigNum($poolInfo['pool_id']);
            $lessList = array_column($lessList['data'], null, 'item_no');

            //检查
            $logs = [];
            foreach($extractInfo as $val) {
                if(empty($val['gift_id']) || empty($val['extract_num']) || empty($lessList[$val['item_no']])) {
                    continue;
                }
                $logs[] = [
                    'extract_pool_id' => $extractPoolId,
                    'pool_id' => $poolInfo['pool_id'],
                    'item_no' => $val['item_no'],
                    'gift_id' => $val['gift_id'],
                    'extract_num' => $val['extract_num'],
                    'true_num' => 0,
                    'admin_id' => $adminId,
                ];
            }
            if(empty($logs)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //记录
            foreach($logs as $key=>$log) {
                $logId = $this->wishWheelModel->addWishWheelExtractLog($log);
                $logs[$key]['log_id'] = $logId;
            }

            //缓存处理
            foreach($logs as $key=>$log) {
                $poolConfigId = $lessList[$log['item_no']]['id'];
                $giftId = $lessList[$log['item_no']]['gift_id'];
                for($i=0;$i<$log['extract_num'];$i++) {
                    //波波球自指定奖池中抽取指定的余量
                    $res = $this->wishWheelModel->drawWishWheelAppoint($log['pool_id'], $poolConfigId, 0);
                    if($res) {
                        //更新
                        $this->wishWheelModel->wishWheelExtractPoolLogIncr($log['log_id'], 1);
                        //记录
                        $this->wishWheelModel->wishWheelExtractPoolDataAdd($extractPoolId, $giftId);
                    }
                }
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 波波球抽取奖池剩余数量
     */
    public function wishWheelPoolExtractLessNum($extractPoolId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if(empty($extractPoolId)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                //查询
                $poolInfo = $this->wishWheelModel->getWishWheelExtractPoolById($extractPoolId);
                if(empty($poolInfo)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                //获取
                $data = $this->wishWheelModel->getWishWheelExtractPoolNum($extractPoolId);

            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '异常:'.$e->getMessage();
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }




}
